import React, { Component } from 'react'
import { useNavigate } from 'react-router'

import { connect } from 'react-redux'
import { logout } from '../../redux/actions'

import { PAGE_SIZE } from '../../utils/constant'
import { reqRoles, reqAddRole, reqUpdateRole } from '../../api/admin'
// import memoryUtils from '../../utils/memoryUtils'
// import storageUtils from '../../utils/storageUtils'
import { formateDate } from '../../utils/dateUtils'

import AddForm from './AddForm'
import SetRoleAuth from './SetRoleAuth'

import {
  Card,
  Button,
  Table,
  Modal,
  message
} from 'antd'

function annoyCom (MessCom) {
  return (props) => {
    const navigate = useNavigate()
    return <MessCom {...props} navigate={navigate} />
  }
}

class Role extends Component {

  state = {
    roles: [],
    role: {},  //选中的role 
    isShowAdd: false,
    isShowSet: false,
  }

  authRef = React.createRef()

  initColumn = () => {
    this.columns = [
      {
        title: '角色名称',
        dataIndex: 'name'
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        render: (create_time) => formateDate(create_time)
      },
      {
        title: '授权时间',
        dataIndex: 'auth_time',
        render: formateDate
      },
      {
        title: '授权人',
        dataIndex: 'auth_name'
      }
    ]
  }

  onRow = (record) => {
    return {
      onClick: event => {
        console.log('点击行');
        this.setState({
          role: record
        })
      }, // 点击行
    };
  }

  getRoles = async () => {
    const result = await reqRoles()
    if (result.status === 0) {
      const roles = result.data
      this.setState({
        roles
      })
    }
  }

  //添加角色
  addRole = () => {
    this.form.validateFields()
      .then(async (value) => {
        const { roleName } = value
        const result = await reqAddRole({ roleName })
        if (result.status === 0) {
          message.success('角色创建成功')
          this.getRoles()
          this.setState({
            isShowAdd: false
          })
        } else {
          message.error('角色创建失败')
        }
      })
      .catch(error => {
        message.error('角色名称必须输入')
      })
  }

  //设置角色权限
  setRoleAuth = async () => {
    const role = this.state.role
    const menus = this.authRef.current.getMenus()
    role.menus = menus
    console.log(role);
    console.log(this.props.user);
    role.auth_name = this.props.user.username
    const result = await reqUpdateRole(role)
    if (result.status === 0) {
      // 如果当前更新的是自己角色的权限, 强制退出
      if (role._id === this.props.user.role._id) {
        // memoryUtils.user = {}
        // storageUtils.removeUser()
        // this.props.navigate('/login', { replace: true })
        this.props.logout()
        message.success('当前用户角色权限被修改，请重新登录')
      } else {
        message.success('设置角色权限成功')
        this.setState({
          roles: [...this.state.roles],
          isShowSet: false
        })
      }
    } else {
      message.error('设置角色权限失败')
    }
  }

  componentDidMount () {
    this.getRoles()
  }

  render () {
    this.initColumn()
    const { roles, role, isShowAdd, isShowSet } = this.state

    const title = (
      <span>
        <Button
          type='primary'
          style={{ marginRight: 20 }}
          onClick={() => this.setState({ isShowAdd: true })}>
          创建角色
        </Button>
        <Button
          type='primary'
          disabled={!role._id}
          onClick={() => this.setState({ isShowSet: true })}
        >
          设置角色权限
        </Button>
      </span>
    )
    return (
      <Card title={title}>
        <Table
          dataSource={roles}
          columns={this.columns}
          rowKey='_id'
          bordered
          rowSelection={{
            type: 'radio',
            selectedRowKeys: [role._id],
            onSelect: (record) => {
              this.setState({
                role: record
              })
            }
          }}
          onRow={this.onRow}
          pagination={{
            defaultPageSize: PAGE_SIZE,
            showQuickJumper: true,
            showTitle: 'true'
          }}
        />
        <Modal
          title="添加角色"
          destroyOnClose
          visible={isShowAdd}
          onOk={this.addRole}
          onCancel={() => {
            this.setState({
              isShowAdd: false
            })
          }}
        >
          <AddForm
            setForm={form => this.form = form}
          />
        </Modal>
        <Modal
          title="设置角色权限"
          destroyOnClose
          visible={isShowSet}
          onOk={this.setRoleAuth}
          onCancel={() => {
            this.setState({
              isShowSet: false
            })
          }}
        >
          <SetRoleAuth role={role} ref={this.authRef} />
        </Modal>
      </Card>
    )
  }
}
export default connect(
  state => ({ user: state.user }),
  { logout }
)(annoyCom(Role))